package com.west.imserver.handler.impl;

import imserverentity.entity.IChattable;
import imserverentity.entity.Protocol;
import imserverentity.entity.impl.Client;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.west.imserver.handler.IHandler;
import com.west.imserver.sender.Sender;
import com.west.imserver.server.IMServer;

public class LogoutHandler implements IHandler {
	private String msgType;
	private Map<String, Object> params;
	
	public LogoutHandler() {}
	public LogoutHandler(String msgType, Map<String, Object> params) {
		this.msgType = msgType;
		this.params = params;
	}
	
	public String getMsgType() {
		return msgType;
	}
	public void setMsgType(String msgType) {
		this.msgType = msgType;
	}
	public Map<String, Object> getParams() {
		return params;
	}
	public void setFrom(Map<String, Object> params) {
		this.params = params;
	}
	
	
	public void handle() throws IOException {
		IChattable from = (IChattable)params.get("from");
		IMServer.senders.remove(from);
		List<String> list = new ArrayList<String>(IMServer.clients.keySet());
		String msg = ((Client) from).getAccount() + " logouts";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("from", from);
		params.put("msg", msg);
		params.put("list", list);
		params.put("status", "200");
		Protocol protocol = new Protocol(msgType, params);
		for(String account : list) {
			ObjectOutputStream ooss = IMServer.senders.get(IMServer.clients.get(account));
			Sender.send(protocol, ooss);
		}
	}
}
